package com.example.reward.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.example.reward.R;
import com.example.reward.api.ApiCallback;
import com.example.reward.api.ApiClient;
import com.example.reward.api.RewardApi;
import com.example.reward.filter.InputFilterMinMax;
import com.example.reward.response.RewardResultDto;
import com.example.reward.response.StudentDto;
import com.example.reward.response.Subject;
import com.google.android.material.card.MaterialCardView;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CalculatorFragment extends Fragment {

    private LinearLayout subjectContainer, resultContainer,overviewContainer;
    private final Map<String, EditText> subjectEditMap = new HashMap<>();
    private static List<Subject> cachedSubjects = null;
    private MaterialCardView resultCard;
    private EditText editRank;
    private final RewardApi rewardApi = ApiClient.getClient().create(RewardApi.class);

    private View spinKit;

    public CalculatorFragment() {
        super(R.layout.fragment_calculator);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_calculator, container, false);

        spinKit = rootView.findViewById(R.id.spin_kit);

        subjectContainer = rootView.findViewById(R.id.subjectContainer);
        loadSubject(rootView);

        editRank = rootView.findViewById(R.id.editRank);
        editRank.setFilters(new InputFilter[]{
                new InputFilterMinMax(1, Integer.MAX_VALUE)
        });
        resultCard = rootView.findViewById(R.id.resultCard);
        overviewContainer = rootView.findViewById(R.id.overviewContainer);
        resultContainer = rootView.findViewById(R.id.rewardContainerLayout);

        Button btnCalculate = rootView.findViewById(R.id.btnCalculate);

        btnCalculate.setOnClickListener(v -> calculateReward(rootView));

        return rootView;
    }

    private void loadSubject(View rootView) {
        spinKit.setVisibility(View.VISIBLE);
        if (cachedSubjects != null) {
            // 如果已缓存，直接用
            for (Subject subject : cachedSubjects) {
                addSubjectInput(subject);
            }
            spinKit.setVisibility(View.GONE);
            return;
        }

        // 否则调用接口加载
        rewardApi.getSubjects().enqueue(new ApiCallback<>() {
            @Override
            public void onSuccess(List<Subject> subjects) {
                cachedSubjects = subjects; // 缓存
                for (Subject subject : subjects) {
                    addSubjectInput(subject);
                }
                spinKit.setVisibility(View.GONE);
            }

            @Override
            public void onError(String errorMsg) {
                Snackbar.make(rootView, "加载科目失败：" + errorMsg, Snackbar.LENGTH_LONG).show();
                spinKit.setVisibility(View.GONE);
            }
        });
    }

    private void addSubjectInput(Subject subject) {
        String subjectName = subject.getName();
        int fullScore = subject.getFull();

        LayoutInflater inflater = LayoutInflater.from(getContext());
        View inputView = inflater.inflate(R.layout.item_subject_input, subjectContainer, false);

        TextInputLayout inputLayout = inputView.findViewById(R.id.inputLayout);
        TextInputEditText editText = inputView.findViewById(R.id.editText);

        inputLayout.setHint(subjectName + "成绩" + "（满分" + fullScore + "）");
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);

        // 添加最大值限制
        editText.setFilters(new InputFilter[]{
                new InputFilterMinMax(0, fullScore)
        });

        subjectEditMap.put(subjectName, editText);
        subjectContainer.addView(inputView);
    }

    private void calculateReward(View rootView) {
        StudentDto request = getStudentDto();
        if (request == null) {
            return; // 校验未通过，不继续提交
        }

        spinKit.setVisibility(View.VISIBLE);
        rewardApi.calculateReward(request).enqueue(new ApiCallback<>() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(RewardResultDto result) {
                // 成功逻辑
                setSuccessResult(result);
                spinKit.setVisibility(View.GONE);
            }

            @Override
            public void onError(String errorMsg) {
                Snackbar.make(rootView, "计算出错：" + errorMsg, Snackbar.LENGTH_LONG).show();
                spinKit.setVisibility(View.GONE);
            }
        });
        spinKit.setVisibility(View.GONE);
    }

    @Nullable
    private StudentDto getStudentDto() {
        boolean hasError = false;
        HashMap<String, Integer> scores = new HashMap<>();

        for (Map.Entry<String, EditText> entry : subjectEditMap.entrySet()) {
            String subject = entry.getKey();
            EditText edit = entry.getValue();
            String value = edit.getText().toString().trim();
            if (value.isEmpty()) {
                edit.setError("请输入" + subject + "成绩");
                hasError = true;
            } else {
                scores.put(subject, Integer.parseInt(value));
            }
        }

        if (isEmpty(editRank)) {
            editRank.setError("请输入排名");
            hasError = true;
        }

        if (hasError) return null;

        return new StudentDto(scores, parse(editRank));
    }

    private boolean isEmpty(EditText editText) {
        return TextUtils.isEmpty(editText.getText().toString().trim());
    }

    private void setSuccessResult(RewardResultDto result) {
        resultCard.setVisibility(View.VISIBLE); // 显示结果区域

        overviewContainer.removeAllViews();  // 建议添加清理逻辑
        resultContainer.removeAllViews();    // 清空旧的内容

        // 设置总览文字
        String totalDesc = "奖励总金额：" + result.getTotalReward() +
                "\n总分：" + result.getTotal() +
                "（核心：" + result.getCoreTotal() +
                "，综合：" + result.getGeneralTotal() + "）" +
                "\n当前排名：" + result.getCurrentRank();
        addRewardOverviewCard(totalDesc);

        // 准备奖励项数据（你也可以用 List 存）
        Map<String, String> rewardMap = new LinkedHashMap<>();
        rewardMap.put("基础奖励（" + result.getBase() + "）", "\n达标条件：" + result.getBaseDesc());
        rewardMap.put("额外奖励（" + result.getExtra() + "）", "\n额外条件：" + result.getExtraDesc());
        rewardMap.put("特殊奖励（" + result.getSpecial() + "）", "\n特殊说明：" + result.getSpecialDesc());

        resultContainer.removeAllViews(); // 清空旧的

        for (Map.Entry<String, String> entry : rewardMap.entrySet()) {
            View cardView = createRewardCard(entry.getKey(), entry.getValue());
            resultContainer.addView(cardView);
        }
    }

    public void addRewardOverviewCard(String totalDesc){
        Context context = requireContext();  // 获取上下文

        overviewContainer.removeAllViews();  // 清空旧的内容，避免叠加

        // 添加分割线
        View divider = new View(context);
        LinearLayout.LayoutParams dividerParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 1);
        dividerParams.setMargins(0, 16, 0, 16);
        divider.setLayoutParams(dividerParams);
        divider.setBackgroundColor(Color.parseColor("#DDDDDD"));
        overviewContainer.addView(divider);

        // 添加标题
        TextView overviewTitle = new TextView(context);
        overviewTitle.setText("奖励概览");
        overviewTitle.setTextColor(ContextCompat.getColor(context, R.color.black));
        overviewTitle.setTextSize(18);
        overviewTitle.setTypeface(Typeface.DEFAULT_BOLD);
        overviewTitle.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        overviewContainer.addView(overviewTitle);

        // 添加内容（如奖励项）
        TextView rewardItem = new TextView(context);
        rewardItem.setText(totalDesc);
        rewardItem.setTextSize(16);
        rewardItem.setTextColor(Color.DKGRAY);
        rewardItem.setPadding(0, 8, 0, 0);
        overviewContainer.addView(rewardItem);
    }

    private View createRewardCard(String title, String content) {
        Context context = requireContext();

        // 外层 MaterialCardView
        MaterialCardView card = new MaterialCardView(context);
        LinearLayout.LayoutParams cardParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
        );
        cardParams.setMargins(0, 0, 0, 16);
        card.setLayoutParams(cardParams);
        card.setCardElevation(2);
        card.setStrokeWidth(1);
        card.setStrokeColor(ContextCompat.getColor(context, R.color.gray));
        card.setRadius(8);
        card.setBackgroundTintList(ColorStateList.valueOf(Color.WHITE));

        // 内部内容 LinearLayout
        LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(24, 24, 24, 24);

        // 标题
        TextView titleView = new TextView(context);
        titleView.setText(title);
        titleView.setTextSize(16);
        titleView.setTypeface(null, Typeface.BOLD);
        titleView.setTextColor(ContextCompat.getColor(context, R.color.black));

        // 内容
        TextView contentView = new TextView(context);
        contentView.setText(content);
        contentView.setTextSize(14);
        contentView.setPadding(0, 8, 0, 0);
        contentView.setTextColor(ContextCompat.getColor(context, R.color.black));

        layout.addView(titleView);
        layout.addView(contentView);
        card.addView(layout);

        return card;
    }


    private int parse(EditText edit) {
        String str = edit.getText().toString().trim();
        return str.isEmpty() ? 0 : Integer.parseInt(str);
    }
}
